package com.tth.learn.addproperties.java;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 解决线程安全问题的方法三：Lock锁
 *
 * @Author tth
 * @Date 2022/11/1 17:11
 */
public class LockTest {
    public static void main(String[] args) {
        Window5 w5 = new Window5();
        Thread t1 = new Thread(w5);
        Thread t2 = new Thread(w5);
        Thread t3 = new Thread(w5);
        t1.start();
        t2.start();
        t3.start();
    }
}

class Window5 implements Runnable {
    private int ticket = 100;
    // 1.实例化lock
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                // 2.调用lock()加锁
                lock.lock();
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "售票，票号为：" + ticket);
                    ticket--;
                } else {
                    break;
                }
            } finally {
                // 3.调用unlock()释放锁
                lock.unlock();
            }
        }
    }
}
